package work.mediway.mdm.biz.job;

import com.xxl.job.core.handler.annotation.XxlJob;

import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import work.mediway.mdm.core.constant.JobConstant;
import work.mediway.mdm.biz.entity.biz.UserBTEventLog;
import work.mediway.mdm.biz.service.biz.UserBTEventLogService;
import work.mediway.mdm.biz.service.patient.PaAddressService;
import work.mediway.mdm.biz.service.patient.PaPatientService;
import work.mediway.mdm.biz.vo.patient.StatisticsPatientNumVO;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2020/8/5
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PatientStatisticsJob {

    private final PaAddressService paAddressService;
    private final PaPatientService paPatientService;
    private final UserBTEventLogService userBtEventLogService;

    /**
     * Scheduled(cron = "0 0 0 * * ? ")
     * 每天12点运行
     */
    @XxlJob("patientAreaHandler")
    public void patientAreaHandler() {
        log.info("========================== 定时任务统计患者地区分布 开始 ==========================");
        Map<String, List<Map<String, Object>>> numByArea = paAddressService.statisticsNumByArea(null);
        UserBTEventLog userBtEventLog = new UserBTEventLog(JobConstant.CONST_PATIENT_AREA_STATISTICS_KEY
                , JSONUtil.toJsonStr(numByArea), DateUtil.today());
        this.userBtEventLogService.saveBtEventLog(userBtEventLog);
        log.info("========================== 定时任务统计患者地区分布 完成 ==========================");
    }

    /**
     * Scheduled(cron = "0 0 0 * * ? ")
     * 每天12点运行
     */
    @XxlJob("patientAgeHandler")
    public void patientAgeHandler() {
        log.info("========================== 定时任务统计患者年龄分布 开始 ==========================");
        Map<String, Object> numByArea = paPatientService.statisticsNumAge();
        UserBTEventLog userBtEventLog = new UserBTEventLog(JobConstant.CONST_PATIENT_AGE_STATISTICS_KEY
                , JSONUtil.toJsonStr(numByArea), DateUtil.today());
        this.userBtEventLogService.saveBtEventLog(userBtEventLog);
        log.info("========================== 定时任务统计患者年龄分布 完成 ==========================");
    }

    /**
     * Scheduled(cron = "0 0 0 * * ? ")
     * 每天12点运行
     * 统计患者总览
     * 记录每天最后一次统计时的患者ID，下次统计时直接从此处开始
     */
    @XxlJob("patientHandler")
    public void patientHandler() {
        log.info("========================== 定时任务统计患者总览 开始 ==========================");
        StatisticsPatientNumVO numPatient = paPatientService.statisticsPatient();

        UserBTEventLog userBtEventLog = this.userBtEventLogService.buildPatientEventLog(numPatient);
        this.userBtEventLogService.saveBtEventLog(userBtEventLog);
        log.info("========================== 定时任务统计患者总览 完成 ==========================");
    }

}